﻿namespace TestAppSite.Controllers
{
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using TestAppSite.Models;

    public class UploadsController : Controller
    {
        //
        // GET: /Uploads/

        public ActionResult Index()
        {
            var model = this.TempData["UploadedFile"];
            return View(model);
        }

        [HttpPost]
        public async Task<ActionResult> Index(HttpPostedFileBase file)
        {
            if (file != null)
            {
                var hashAlgorithm = MD5.Create();
                var buffer = new byte[file.ContentLength];
                var bytes = await file.InputStream.ReadAsync(buffer, 0, buffer.Length);
                var hash = hashAlgorithm.ComputeHash(buffer, 0, bytes);
                var model = new UploadFileViewModel
                {
                    Filename = Path.GetFileName(file.FileName),
                    ContentType = file.ContentType,
                    MD5 = BitConverter.ToString(hash),
                    Content = buffer
                };

                this.TempData["UploadedFile"] = model;
            }

            return RedirectToAction("Index");
        }
    }
}
